package com.chukun.rpc.consumer.proxy;

import com.chukun.rpc.protocol.InvokerProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 */
public class RpcProxy {

    public static <T> T create(Class<?> clazz) {
        MethodProxy proxy = new MethodProxy(clazz);
        Class[] interfaces = clazz.isInterface()?new Class[]{clazz} : clazz.getInterfaces();
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(),interfaces,proxy);
    }

    /**
     * 动态代理实现类
     */
    private static class MethodProxy  implements InvocationHandler {

        private Class<?> targetClazz;

        public MethodProxy(Class<?> targetClazz) {
            this.targetClazz = targetClazz;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this,args);
            } else {
                return rpcInvoke(proxy,method,args);
            }
        }

        /**
         * 实现接口的核心方法
         * @param proxy
         * @param method
         * @param args
         * @return
         */
        public  Object rpcInvoke(Object proxy,Method method,Object[] args) {
            // 传输协议
            InvokerProtocol protocol = new InvokerProtocol();
            protocol.setClassName(this.targetClazz.getName());
            protocol.setMethodName(method.getName());
            protocol.setParamters(method.getParameterTypes());
            protocol.setParamterValues(args);

            final RpcProxyHandler consumerHandler = new RpcProxyHandler();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try{
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(workerGroup)
                        .channel(NioSocketChannel.class)
                        .option(ChannelOption.TCP_NODELAY,true)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast("binaryEncoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                                pipeline.addLast(new LengthFieldPrepender(4));
                                pipeline.addLast("objectEncoder",new ObjectEncoder());
                                pipeline.addLast("objectDecoder",new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                                pipeline.addLast(consumerHandler);
                            }
                        });
                ChannelFuture future = bootstrap.connect("localhost", 8080).sync();
                future.channel().writeAndFlush(protocol).sync();
                future.channel().closeFuture().sync();
            }catch (Exception e) {
                  e.printStackTrace();
            }finally {
                workerGroup.shutdownGracefully();
            }
            return consumerHandler.getResponse();
        }
    }
}
